import { unref, Ref, nextTick } from 'vue'
import { Recordable } from "../types/global";

// promise验证表单
export const syncValidate = (formRef: Ref): Promise<object> => {
    return new Promise((resolve, reject) => {
        formRef.value.validate((errors: any) => {
            if (!errors) {
                // const result = await apiAddMenu(form);
                resolve({ errors: null })
            } else {
                reject({ errors: errors })
            }
        })
    })
}

// 重置表格
export const reloadForm = async (formRef: Ref, form: any, defaultForm: () => Object): Promise<void> => {
    await nextTick(() => {
        formRef.value.restoreValidation(); // 去除验证
        form = Object.assign(unref(form), defaultForm()); // 重置数据
    })
}

// dynamic use hooks props
export function getDynamicProps<T, U>(props: T): Partial<U> {
    const ret: Recordable = {};

    Object.keys(props).map((key) => {
        ret[key] = unref((props as Recordable)[key]);
    });

    return ret as Partial<U>;
}

export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
    let key: string;
    for (key in target) {
        src[key] = Object.prototype.toString.call(src[key]) === '[object Object]' ? deepMerge(src[key], target[key]) : (src[key] = target[key]);
    }
    return src;
}



